<template>
  <div class="page-box">
    <TopNav title="InvitePage.yqhy" show_left="true"/>
    <div class="content" v-if="share.url">
      <div v-if="showQrcode" class="drag-wrap">
        <vue-draggable-resizable>
          <img v-if="user.share_qrcode" style="width:100%;height:100%;" :src="user.share_qrcode" alt="">
        </vue-draggable-resizable>
      </div>
      $t('InvitePage.wdfxdz'): <nut-button class="copy copy-share-code" @click="copyShare" data-clipboard-action="copy" :data-clipboard-text="shareUrl+shareCode" small style="background: #535b85;padding:0.1rem;height:auto;border-radius: 0.1rem;">{{ $t('InvitePage.fzewmlj') }}</nut-button>
      <div @click="copyShare"
           v-if="shareUrl && shareCode"
           class="share-address copy copy-share-code"
           data-clipboard-action="copy"
           :data-clipboard-text="shareUrl+shareCode">
        {{shareUrl+shareCode}}
      </div>
      {{ $t('InvitePage.wdfxewm') }}：<nut-button @click="handleClickGenerateQrcode" small style="background: #535b85;padding:0.1rem;height:auto;border-radius: 0.1rem;">{{ $t('InvitePage.sxewmtp') }}</nut-button>
<!--      <nut-button small style="background: #535b85;padding:0.1rem;height:auto;border-radius: 0.1rem;" @click="handleClickSaveQrcode">-->
<!--        <a style="color:#fff;">{{ $t('InvitePage.bcewmtp') }}</a>-->
<!--      </nut-button>-->
      <div style="margin:0.4rem 0;">
        <img v-if="user.share_qrcode" class="qrcode" :src="user.share_qrcode" alt="">
      </div>
      <div v-if="user.share_qrcode" class="btn-download" @click="handleClickSaveQrcode">{{ $t('InvitePage.bcewm') }}</div>
      <div v-if="share.imgs">
        <Slider @changeItem="handleClickChange" itemWidth="33.33333333%" itemHeight="100%" :img-list="share.imgArr"/>
      </div>
    </div>
    <div v-else>
      <EmptyBox text="InvitePage.zwjl" />
    </div>
    <nut-popup :overlay="false" v-model="showBigImg" position="top" :style="{ height: '1000%' }">
      <img @click="handleClickShowClose" style="height: 100%;width: 100%;z-index:10000000;" :src="bigImgUrl" alt="">
    </nut-popup>
    <div v-if="showClose" @click="handleClickCloseDialog" class="close-dialog">{{ $t('InvitePage.tc') }}</div>
  </div>
</template>

<script>
import MainNav from "../components/MainNav";
import TopNav from "../components/TopNav";
import EmptyBox from "../components/EmptyBox";
import Slider from "../components/Slider";
import helper from "../utils/helper";
import VueDraggableResizable from 'vue-draggable-resizable';
import 'vue-draggable-resizable/dist/VueDraggableResizable.css';


export default {
  name: 'InvitePage',
    components: {MainNav,TopNav,EmptyBox,Slider,VueDraggableResizable},
    data () {
    return {
        loading:false,
        user:{},
        share:{},
        isDownloaded: false,
        currSelImgIndex:-1,
        afterImg: '',
        downloadCnt:0,
        showQrcode: false,
        showBigImg: false,
        bigImgUrl: '',
        showClose: false,
        shareUrl: '',
        shareCode: '',
        downloadQrcodeUrl:' ',
    }
  },
    methods:{
        getData(){
            
            this.$axios.get(this.$api_url.user).then((res)=>{
                this.user = res.data;
                this.shareCode = this.user.share_code;
            })
        },
        handleClickSaveQrcode(){
            let url = this.share.imgArr[this.currSelImgIndex];
            try{
                let args = {
                    type:'save_img',
                    data:url
                };
                if(Ak){
                    let loading = this.$toast.loading();
                    Ak.postMessage(JSON.stringify(args));
                    setTimeout(()=>{
                        loading.hide();
                    },3000)
                }

            } catch (e) {
                location.href=url;
            }
        },
        getShare(){
            let loading = this.$toast.loading();
            let url = this.$api_url.get_share;
            this.$axios.get(url).then((res)=>{
                this.share = res.data;
                this.shareUrl = this.share.url+"?invite_code=";
                this.share.imgArr = this.share.imgs.split(",");
                console.log(this.share.imgArr)
            }).catch((err)=>{
                this.$toast.fail(err.message);
            }).then(()=>{
                loading.hide();
            })
        },
        checkOs(){
            var u = navigator.userAgent;
            var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
            var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
            if(isAndroid){
                return 'android';
            } else if(isiOS){
                return 'ios';
            }
            return 'pc';
        },
        handleClickGenerateQrcode(){
            let loading = this.$toast.loading();
            this.$axios.get(this.$api_url.generate_qrcode).then((res)=>{
                if(res.data.code === 0){
                    this.$toast.success(res.data.msg);
                    this.getData();
                    this.getShare();
                } else{
                    this.$toast.fail(res.data.msg);
                }
            }).catch((err)=>{
                this.$toast.fail(err.message);
            }).then(()=>{
                loading.hide()
            })
        },
        copyShare(){
            let clipboard = new this.$clipboard(".copy-share-code");
            clipboard.on('success', ()=> {
                this.$toast.success(this.$t('InvitePage.fzcg'));
            });
            clipboard.on('error', ()=> {
                this.$toast.fail(this.$t('InvitePage.fzsb'));
            });
        },
        handleClickShowClose(){
            this.showClose = !this.showClose;
        },
        handleClickMake(){
            if(this.checkOs() == "android"){
                location.href="app://screenshot?"+this.user.share_qrcode+"&"+this.share.imgArr[this.currSelImgIndex];
            } else{
                this.$toast.text(this.$t('InvitePage.zzhxysdjt'));
                let url = this.share.imgArr[this.currSelImgIndex];
                this.bigImgUrl = url;
                this.showBigImg = true;
                this.showQrcode = true;
            }
        },
        createDownload(url) {
          this.isDownloaded = false;
          this.$toast.loading(this.$t('InvitePage.zzxz')+"...",{
              duration:3000
          });
          var dtask = plus.downloader.createDownload(url, {}, (d, status)=>{
              // 下载完成
              if(status == 200){
                  let filename = d.filename;
                  plus.gallery.save( filename, ()=> {
                      alert(this.$t('InvitePage.yxzwc'));
                  } );
              } else {
                  alert("Download failed: " + status);
              }
            });
            //dtask.addEventListener("statechanged", onStateChanged, false);
            dtask.start();
        },
        handleClickChange(page){
            this.currSelImgIndex = page;
        },
        downloadBg(url){
            var dtask = plus.downloader.createDownload(url, {}, (d, status)=>{
                // 下载完成
                if(status == 200){
                    let filename = d.filename;
                    this.drawBg(filename);
                    this.downloadCnt++;
                    if(this.downloadCnt >= 2){
                        this.makeImage();
                    }
                } else {
                    alert("Download failed: " + status);
                }
            });
            //dtask.addEventListener("statechanged", onStateChanged, false);
            dtask.start();
        },
        handleClickCloseDialog(){
            this.showClose = false;
            this.showBigImg = false;
            this.showQrcode = false;

        },
        drawBg(url){
            let canvas = document.getElementById("myCanvas");
            let context = canvas.getContext("2d");

            let img = new Image();
            img.src = url;
            img.onload = function(){
                // 等比例缩放图片
                let scale = 1;
                context.width = this.width * scale;
                context.height = this.height * scale; // 计算等比缩小后图片
                canvas.width = context.width;
                canvas.height = context.height;

                context.drawImage(this, 0, 0, context.width, context.height);
                // context.drawImage(this, 0, 0, 1080, 980)改变图片大小到1080*980
            }
            // var that = this;
            // html2canvas(that.$refs.box,{
            //     height:100,
            //     width:100
            // }).then(function(canvas) {
            //     console.log(canvas);
            //     that.afterImg = canvas.toDataURL()//将canvas转为base64图片(eg. )
            // });
        },
        downloadQrcode(url){
            var dtask = plus.downloader.createDownload(url, {}, (d, status)=>{
                // 下载完成
                if(status == 200){
                    let filename = d.filename;
                    this.drawQrcode(filename);
                    this.downloadCnt++;
                    if(this.downloadCnt >= 2){
                        this.makeImage();
                    }
                } else {
                    alert("Download failed: " + status);
                }
            });
            //dtask.addEventListener("statechanged", onStateChanged, false);
            dtask.start();
        },
        makeImage(){
            let canvas = document.getElementById("myCanvas")
            let data = canvas.toDataURL();
            this.$toast.text(this.$t('InvitePage.zzhc')+"...");
            this.share.qrcode = data;
            var myBlob = helper.dataURLtoBlob(data);
            var myUrl = URL.createObjectURL(myBlob);
            var dtask = plus.downloader.createDownload(myUrl, {}, (d, status)=>{
                // 下载完成
                if(status == 200){
                    let filename = d.filename;
                    plus.gallery.save( filename, ()=> {
                        alert(this.$t('InvitePage.yxzwc'));
                    } );
                } else {
                    alert("Download failed: " + status);
                }
            });
            //dtask.addEventListener("statechanged", onStateChanged, false);
            dtask.start();

            //helper.downloadFileByBase64(data);
        },
        drawQrcode(url){
            var canvas = document.getElementById("myCanvas")
            var context = canvas.getContext("2d")

            var img = new Image()
            img.src = url;
            let that = this;
            img.onload = function(){
                // 等比例缩放图片
                var scale = 0.6;
                context.width = this.width * scale;
                context.height = this.height * scale; // 计算等比缩小后图片

                context.drawImage(this, canvas.width/2-context.width/2, canvas.height-context.height-context.height/2, context.width, context.height);
               //console.log(canvas.toDataURL());
                // context.drawImage(this, 0, 0, 1080, 980)改变图片大小到1080*980
            }
            // var that = this;
            // html2canvas(that.$refs.box,{
            //     height:100,
            //     width:100
            // }).then(function(canvas) {
            //     console.log(canvas);
            //     that.afterImg = canvas.toDataURL()//将canvas转为base64图片(eg. )
            // });
        },

    },
    mounted() {
      //this.downloadQrcodeUrl = this.$api_url.download_qrcode+"?api_token="+helper.getToken();
      this.getData();
      this.getShare();
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->



<style scoped>
  .page-box{
    padding-top:2rem;
    height: 100%;
    background: url("/static/img/profile-bg.png");
  }
  .content{
    height:100%;
    background-repeat: no-repeat;
    background-size: 100% 100%;
  }
  .bottom-box{
    position: fixed;
    bottom: 2.4rem;
    width: 100%;
  }
  .qrcode{
    height:3rem;
    width:3rem;
    box-shadow: 0 0 0.6rem #555;
  }
  .download{
    height: 3rem;
    width: 3rem;
    position: absolute;
    bottom: 4rem;
    opacity: 0.8;
    right: 3.5rem;
  }
  .share-address{
    width: 70%;
    margin: 0.3rem auto;
    background-color: #636363;
    color: #fff;
    padding: 0.2rem;
    border-radius: 0.1rem;
  }
  .btn-download{
    background-color: #256bbb;
    color:#fff;
    width:4rem;
    padding:0.2rem;
    margin: 0.5rem auto;
    border-radius: 0.1rem;
  }
  #myCanvas{
    position: absolute;
    left:-1000px;
  }
  .vdr{
    border-color:transparent;
    z-index:3000 !important;
  }
  .close-dialog{
    position: absolute;
    top: 0;
    z-index: 10000001;
    padding: 0.5rem 1rem;
    color: #fff;
    left: 0;
    width: 100%;
    background: rgba(255,255,255,0.3);
  }
  .drag-wrap{
    z-index: 10000001;
  }


</style>
